package com.hengxinguotong.zhihuichengjian.ui.material;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Material;
import com.hengxinguotong.zhihuichengjian.bean.MaterialBean;
import com.hengxinguotong.zhihuichengjian.bean.Weighbridge;
import com.hengxinguotong.zhihuichengjian.bean.WeighbridgeRes;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectListPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 材料登记
 * Created by liux on 2017/3/20.
 */

public class MaterialRegistrationActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {

    @BindView(R.id.order_no_rl)
    RelativeLayout orderNoRl;
    @BindView(R.id.order_no_tv)
    HXTextView orderNoTv;
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.main_ll)
    LinearLayout mainLl;
    @BindView(R.id.name_tv)
    HXTextView nameTv;
    @BindView(R.id.model_tv)
    HXTextView modelTv;
    @BindView(R.id.manufacturer_etv)
    HXEditTextView manufacturerEtv;
    @BindView(R.id.num_etv)
    HXEditTextView numEtv;
    @BindView(R.id.unit_tv)
    HXTextView unitTv;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.live_switch_bt)
    Switch liveSwitchBt;
    @BindView(R.id.sampling_time_tv)
    HXTextView samplingTimeTv;
    @BindView(R.id.result_switch_bt)
    Switch resultSwitchBt;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.remark_etv)
    HXEditTextView remarkEtv;
    private List<String> paths;
    private List<String> minPaths;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private AlertDialog dialog;
    private Material material;
    private MaterialBean materialBean, modelBean;
    private String materialBeanId, modelBeanId;
//    private int experimentResult = 2;
//    private int siteResult = 2;
    private String weighbridgeId = null;//地磅ID
    private SelectListPop mSelectPop;
    private boolean hasEdit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_registration);
        ButterKnife.bind(this);
        material = (Material) getIntent().getSerializableExtra("material");
        hasEdit = getIntent().getBooleanExtra("hasEdit", false);
        initView();
//        getWeighbridge("加载中…");
    }

    private void initView() {
        if (material != null) {
            orderNoRl.setVisibility(View.VISIBLE);
            Utils.setEditTextViewUnable(material.getOrderNo(), orderNoTv);
            if(material.getExperimentResult() == 1){
                resultSwitchBt.setChecked(true);
            }else if(material.getExperimentResult() == 2){
                resultSwitchBt.setChecked(false);
            }
            if(material.getSiteResult() == 1){
                liveSwitchBt.setChecked(true);
            }else if(material.getSiteResult() == 2){
                liveSwitchBt.setChecked(false);
            }
            if(hasEdit){
                saveTest.setText("修改");
                nameTv.setText(material.getName());
                modelTv.setText(material.getModel());
                manufacturerEtv.setText(material.getManufacturer());
                materialBeanId = material.getMaterialId() ;
                modelBeanId = material.getModelId();
                numEtv.setText(material.getQuantity() + "");
                dateTv.setText(material.getApproachDate());
                unitTv.setText(material.getUnit());
                remarkEtv.setText(material.getRemark());
                samplingTimeTv.setText(material.getSamplingDate());
                paths = new ArrayList<String>();
                paths.add(Utils.ADDPIC);
                addPicRv.setLayoutManager(getLinearLayoutManager());
                aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
                addPicRv.setAdapter(aualityTestAddPicAdapter);
                if (null != material.getFilePathList() && material.getFilePathList().size() > 0) {
                    loadImages(material.getFilePathList());
                }
            }else{
                saveTest.setVisibility(View.GONE);
                orderNoRl.setVisibility(View.GONE);
                Utils.setEditTextViewUnable(material.getName(), nameTv);
                Utils.setEditTextViewUnable(material.getModel(), modelTv);
                Utils.setEditTextViewUnable(material.getManufacturer(), manufacturerEtv);
                Utils.setEditTextViewUnable(material.getQuantity() + "", numEtv);
                Utils.setEditTextViewUnable(material.getApproachDate(), dateTv);
                Utils.setEditTextViewUnable(material.getUnit()+"", unitTv);
                Utils.setEditTextViewUnable(material.getSamplingDate(), samplingTimeTv);
                Utils.setEditTextViewUnable(material.getRemark(), remarkEtv);
                resultSwitchBt.setEnabled(false);
                liveSwitchBt.setEnabled(false);
                if (null == material.getFilePathList() || material.getFilePathList().size() <= 0) {
                    noPicTv.setVisibility(View.VISIBLE);
                    addPicRv.setVisibility(View.GONE);
                } else {
                    addPicRv.setLayoutManager(getLinearLayoutManager());
                    paths = material.getFilePathList();
                    aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                    addPicRv.setAdapter(aualityTestAddPicAdapter);
                }
            }
        } else {
            paths = new ArrayList<String>();
            paths.add(Utils.ADDPIC);
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
            addPicRv.setLayoutManager(getLinearLayoutManager());
            addPicRv.setAdapter(aualityTestAddPicAdapter);
            Calendar c = Calendar.getInstance();
            dateTv.setText(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH));
        }
//        resultSwitchBt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if(isChecked){
//                    siteResult = 1;
//                }else{
//                    siteResult = 2;
//                }
//            }
//        });
//        liveSwitchBt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if(isChecked){
//                    experimentResult = 1;
//                }else{
//                    experimentResult = 2;
//                }
//            }
//        });
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.date_tv, R.id.sampling_time_tv, R.id.name_tv, R.id.model_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.date_tv:
                showWheelViewDialog(dateTv);
                break;
            case R.id.sampling_time_tv:
                showWheelViewDialog(samplingTimeTv);
                break;
            case R.id.name_tv:
                intent = new Intent(this, MaterialListActivity.class);
                intent.putExtra("type", MaterialListActivity.MATERIALTYPE);
                startActivityForResult(intent, 1001);
                break;
            case R.id.model_tv:
                if(materialBeanId != null){
                    intent = new Intent(this, MaterialListActivity.class);
                    intent.putExtra("type", MaterialListActivity.MODELTYPE);
                    intent.putExtra("materialId", materialBeanId);
                    startActivityForResult(intent, 1002);
                }else{
                    showToast("请先选择材料名称");
                }
                break;
        }
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }


    private void getMinImage() {
        if (!checkContent()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size(); i++) {
                        if(paths.get(i).equals(Utils.ADDPIC)){
                            continue;
                        }
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    addMaterial();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addMaterial();
        }

    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
//            tempStrings.remove(Utils.ADDPIC);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (v.getId() == R.id.item_imageview) {
                TaskBigImgActivity.startActivity(MaterialRegistrationActivity.this, (ArrayList<String>) paths, position);
            } else if(v.getId() == R.id.del_iv){
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//            paths.add(Utils.ADDPIC);
            if (aualityTestAddPicAdapter != null) {
                aualityTestAddPicAdapter.setPaths(paths);
            }
        }
        if (resultCode == 1001 && data != null){
            materialBean = (MaterialBean) data.getSerializableExtra("material");
            materialBeanId = materialBean.getId();
            nameTv.setText(materialBean.getName());
            unitTv.setText(materialBean.getUnit());
            modelTv.setText("");
            modelBeanId = null;
        } else if (resultCode == 1002 && data != null){
            modelBean = (MaterialBean) data.getSerializableExtra("model");
            modelBeanId = modelBean.getId();
            modelTv.setText(modelBean.getName());
        }
    }


    private boolean checkContent() {
        if(null == material){
            if(null == materialBean){
                showToast("请选择材料名称");
                return false;
            }

            if (null == modelBean) {
                showToast("请选择规格型号");
                return false;
            }
        }else{
            if(null == materialBeanId){
                showToast("请选择材料名称");
                return false;
            }

            if (null == modelBeanId) {
                showToast("请选择规格型号");
                return false;
            }
        }

        if (Utils.isEmpty(manufacturerEtv.getEditableText().toString())) {
            showToast("请填写生产厂家");
            return false;
        }

        if (Utils.isEmpty(numEtv.getEditableText().toString())) {
            showToast("请填写进场数量");
            return false;
        }

        if (Utils.isEmpty(dateTv.getText().toString())) {
            showToast("请选择进场时间");
            return false;
        }

//        if(Utils.isEmpty(weighbridgeId)){
//            showToast("暂无地磅信息");
//            return false;
//        }
        return true;
    }

    private void getWeighbridge(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/material/getWeighbridge/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    WeighbridgeRes weighbridgeRes = gson.fromJson(json, WeighbridgeRes.class);
                    if(weighbridgeRes.getStatus() == 1){
                        if(null != weighbridgeRes.getValue()){
                            process(weighbridgeRes.getValue());
                        }else{
                            showToast("地磅信息为空");
                        }
                    }else{
                        showToast(weighbridgeRes.getMsg());
                    }
                }

            }

            @Override
            public void onFailure(String json) {
                weighbridgeId = null;
            }
        });
    }

    private void process(Weighbridge weighbridge){
        weighbridgeId = weighbridge.getWeighbridgeId();
        numEtv.setText(String.valueOf(weighbridge.getQuantity()));
        if(weighbridge.getPathArray() != null){
            loadImages(weighbridge.getPathArray());
        }
    }

    public static final int GET_DATA_SUCCESS = 1;
    public static final int NETWORK_ERROR = 2;
    public static final int SERVER_ERROR = 3;
    private File cache;//缓存路径
    //子线程不能操作UI，通过Handler设置图片
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case GET_DATA_SUCCESS:
                    if (aualityTestAddPicAdapter != null) {
                        aualityTestAddPicAdapter.setPaths(paths);
                        aualityTestAddPicAdapter.notifyDataSetChanged();
                    }else{
                        addPicRv.setLayoutManager(getLinearLayoutManager());
                        aualityTestAddPicAdapter = new AualityTestAddPicAdapter(MaterialRegistrationActivity.this, paths,
                                MaterialRegistrationActivity.this, true);
                        addPicRv.setAdapter(aualityTestAddPicAdapter);
                    }
                    break;
                case NETWORK_ERROR:
                    showToast("网络连接失败");
                    break;
                case SERVER_ERROR:
                    showToast("服务器发生错误");
                    break;
            }
        }
    };

    ///下载网络图片
    private void loadImages(List<String> netPaths){

        for (int i = 0; i < netPaths.size(); i++) {
            final String path = netPaths.get(i);
            //开启一个线程用于联网
            new Thread() {
                @Override
                public void run() {
                    try {
                        //把传过来的路径转成URL
                        URL url = new URL(path);
                        //获取连接
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        //使用GET方法访问网络
                        connection.setRequestMethod("GET");
                        //超时时间为10秒
                        connection.setConnectTimeout(10000);
                        //连接设置获得数据流
                        connection.setDoInput(true);
                        //使用缓存
                        connection.setUseCaches(true);
                        //这句可有可无，没有影响
                        connection.connect();
                        //获取返回码
                        int code = connection.getResponseCode();
                        if (code == 200) {
                            InputStream inputStream = connection.getInputStream();
                            //使用工厂把网络的输入流生产Bitmap
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            //关闭数据流
                            inputStream.close();
                            //保存至本地
                            File fileDir = new File(FileUtil.imageDir1);
                            if(!fileDir.exists()){
                                fileDir.mkdirs();
                            }
                            File imgFile=new File(cache,FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg");
                            Log.e("imgFile", "imgFile.getParent===>>>" + imgFile.getParent());
                            Log.e("imgFile", "imgFile.getPath===>>>" + imgFile.getPath());
                            Log.e("imgFile", "imgFile.getAbsolutePath===>>>" + imgFile.getAbsolutePath());
                            Log.e("imgFile", "imgFile.getCanonicalPath===>>>" + imgFile.getCanonicalPath());
                            Log.e("imgFile", "imgFile.getName===>>>" + imgFile.getName());
                            Log.e("imgFile", "imgFile.getAbsoluteFile===>>>" + imgFile.getAbsoluteFile());
                            Log.e("imgFile", "imgFile.getCanonicalFile===>>>" + imgFile.getCanonicalFile());
                            Log.e("imgFile", "imgFile.getParentFile===>>>" + imgFile.getParentFile());
                            Log.e("imgFile", "imgFile.getFreeSpace===>>>" + imgFile.getFreeSpace());
                            Log.e("imgFile", "imgFile.getTotalSpace===>>>" + imgFile.getTotalSpace());
                            Log.e("imgFile", "imgFile.getUsableSpace===>>>" + imgFile.getUsableSpace());
                            try {
                                BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(imgFile));
                                bitmap.compress(Bitmap.CompressFormat.JPEG,80,bos);
                                bos.flush();
                                bos.close();
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            synchronized (this){
                                paths.add(imgFile.getPath());
                                //利用Message把图片发给Handler
                                Message msg = Message.obtain();
                                msg.what = GET_DATA_SUCCESS;
                                handler.sendMessage(msg);
                            }
                        }else {
                            //服务启发生错误
                            handler.sendEmptyMessage(SERVER_ERROR);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        //网络连接错误
                        handler.sendEmptyMessage(NETWORK_ERROR);
                    }
                }
            }.start();

        }

    }

    private class LoadImageThread extends Thread{

    }

    private void addMaterial() {
        if (!checkContent()) {
            return;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this,"constructionid"));
        if(null != material){
            params.addBodyParameter("id", material.getApproachId());
        }
        if(materialBean == null){
            params.addBodyParameter("materialId", material.getMaterialId());
        }else{
            params.addBodyParameter("materialId", materialBean.getId());
        }
        if(modelBean == null){
            params.addBodyParameter("modelId", material.getModelId());
        }else{
            params.addBodyParameter("modelId", modelBean.getId());
        }
        params.addBodyParameter("manufacturer", manufacturerEtv.getEditableText().toString());
//        params.addBodyParameter("weighbridgeId", weighbridgeId);
        params.addBodyParameter("quantity", numEtv.getEditableText().toString());
        params.addBodyParameter("approachDate", dateTv.getText().toString());
        if(liveSwitchBt.isChecked()){
            params.addBodyParameter("siteResult", "1");
        }else{
            params.addBodyParameter("siteResult", "2");
        }
        if (!Utils.isEmpty(samplingTimeTv.getText().toString()))
            params.addBodyParameter("samplingDate", samplingTimeTv.getText().toString());
        if(resultSwitchBt.isChecked()){
            params.addBodyParameter("experimentResult", "1");
        }else{
            params.addBodyParameter("experimentResult", "2");
        }
        if (!Utils.isEmpty(remarkEtv.getText().toString()))
            params.addBodyParameter("remark", remarkEtv.getEditableText().toString());
        if(minPaths.size() > 0){
            for (int i = 0; i < minPaths.size(); i++) {
                params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
            }
        }
        Utils.requestData(getResources().getString(R.string.loading), this, "/material/addApproach/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("提交成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {
                showToast(json);
            }
        });
    }

    private void showWheelViewDialog(final TextView dataTextView) {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        dataTextView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }

}
